<!DOCTYPE html>

<html>
<head>
    <meta charset="UTF-8">
    <title>WebSocket 聊天室</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .status-bar {
            padding: 10px;
            margin-bottom: 20px;
            background: #f0f0f0;
            border-radius: 5px;
        }
        #messages {
            height: 400px;
            overflow-y: auto;
            border: 1px solid #ddd;
            padding: 15px;
            margin-bottom: 20px;
            background: white;
        }
        .message {
            margin: 10px 0;
            padding: 8px;
            border-radius: 5px;
        }
        .private {
            background: #fff3cd;
            border-left: 4px solid #ffc107;
        }
        .group {
            background: #d4edda;
            border-left: 4px solid #28a745;
        }
        .sender {
            font-weight: bold;
            color: #333;
        }
        .controls {
            display: grid;
            grid-gap: 10px;
        }
        input, textarea, button, select {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        button {
            background: #007bff;
            color: white;
            border: none;
            cursor: pointer;
        }
        button:hover {
            background: #0056b3;
        }
        .hidden {
            display: none;
        }

        .message.local {
            opacity: 0.7;
            border-left: 4px solid #6c757d;
        }

        /* 新增样式 */
        .private-send {
            background: #cce5ff;
            border-left: 4px solid #007bff;
        }
        .private-receive {
            background: #fff3cd;
            border-left: 4px solid #ffc107;
        }
        .message-content {
            padding: 5px 0;
        }
        .timestamp {
            color: #666;
            font-size: 0.8em;
            padding: 10px;
        }


        .online-users {
            margin-bottom: 20px;
            background: #f8f9fa;
            padding: 15px;
            border-radius: 5px;
            border: 1px solid #ddd;
        }

        .online-users h3 {
            margin: 0 0 10px 0;
            color: #333;
        }

        #userList {
            list-style: none;
            padding: 0;
            margin: 0;
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
        }

        #userList li {
            background: #e9ecef;
            padding: 4px 12px;
            border-radius: 15px;
            font-size: 0.9em;
        }

        .message-rank {
            margin: 20px 0;
            padding: 15px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            overflow-y: auto;
            max-height: 190px;
        }

        .message-rank h3 {
            margin: 0 0 15px 0;
            color: #2c3e50;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .message-rank button {
            padding: 4px 12px;
            background: #3498db;
            border-radius: 15px;
            font-size: 0.9em;

        }

        #rankList {
            padding: 0;
            margin: 0;
            counter-reset: rank-counter;
        }

        #rankList li {
            padding: 10px;
            margin: 8px 0;
            background: #f8f9fa;
            border-radius: 6px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            transition: transform 0.3s ease;
        }

        #rankList li:hover {
            transform: translateX(5px);
        }

        #rankList li::before {
            counter-increment: rank-counter;
            content: counter(rank-counter);
            width: 25px;
            height: 25px;
            background: #3498db;
            color: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 10px;
        }

        #rankList li:nth-child(1)::before { background: #e74c3c; }
        #rankList li:nth-child(2)::before { background: #f1c40f; }
        #rankList li:nth-child(3)::before { background: #2ecc71; }


    </style>
</head>
<body>
<div class="status-bar">
    状态：<span id="status">未连接</span>
</div>

<div class="online-users">
    <h3>在线用户 (<span id="onlineCount">0</span>)</h3>
    <ul id="userList"></ul>
</div>

<div class="message-rank">
    <h3>消息排行榜 <button onclick="refreshRank()">刷新</button></h3>
    <ol id="rankList"></ol>
</div>

<div id="messages"></div>

<div class="controls">
    <div>
        <input type="text" id="username" placeholder="输入用户名" style="width: 200px;">
        <button onclick="handleConnect()">连接/断开</button>
    </div>

    <textarea id="messageInput" placeholder="输入消息内容" rows="3"></textarea>

    <div style="display: flex; gap: 10px;">
        <select id="messageType" onchange="togglePrivateField()" style="flex: 1;">
            <option value="GROUP">群发消息</option>
            <option value="PRIVATE">私聊消息</option>
        </select>
        <input type="text" id="toUser" placeholder="接收用户" class="hidden" style="flex: 1;">
    </div>

    <button onclick="sendMessage()">发送消息</button>
</div>

<script>
    let ws = null;
    let currentUser = '';

    function handleConnect() {
        const usernameInput = document.getElementById('username');
        if (ws && ws.readyState === WebSocket.OPEN) {
            ws.close();
            //刷新页面
            location.reload();
            return;
        }

        currentUser = usernameInput.value.trim();
        if (!currentUser) {
            alert('请输入用户名');
            return;
        }

        connectWebSocket(currentUser);
    }

    function connectWebSocket(username) {
        const url = `ws://localhost:8080/chat?user=${encodeURIComponent(username)}`;
        ws = new WebSocket(url);

        ws.onopen = () => {
            updateStatus('已连接（用户：' + username + '）');
        };

        ws.onmessage = (event) => {
            const data = event.data; // 注意：直接使用原始字符串
            console.log('Received raw data:', data);

            // 先检查是否是 ONLINE_USERS 消息
            if (data.startsWith("ONLINE_USERS:")) {
                const users = data.substring("ONLINE_USERS:".length).split(',');
                console.log('当前在线用户:', users);
                updateOnlineUsers(users);
                return;
            }

            if (data.startsWith("Rank[")) {
                try {
                    const jsonStr = data.replace("Rank", "");
                    const rankingData = JSON.parse(jsonStr);
                    console.log('排行榜数据:', rankingData);
                    updateRankList(rankingData);
                } catch (e) {
                    console.error('排行榜数据解析失败:', e);
                }
                return; // 处理完成后直接返回
            }
            // 否则尝试解析为 JSON
            else {
                try {
                    const message = JSON.parse(data);
                    displayMessage(message);
                } catch (e) {
                    console.error('消息解析失败:', e);
                }
            }
        };

        ws.onclose = () => {
            updateStatus('未连接');
            currentUser = '';
        };

        ws.onerror = (error) => {
            console.error('WebSocket错误:', error);
            updateStatus('连接错误');
        };
    }


    function updateRankList(rankingData) {
        const rankList = document.getElementById('rankList');
        rankList.innerHTML = '';

        rankingData.slice(0, 10).forEach((item, index) => {
            const li = document.createElement('li');
            li.innerHTML = `            <span>${item.username}</span>
            <span>${item.messageCount} 条消息</span>
        `;

            // 添加奖杯图标
            if (index < 3) {
                const trophy = document.createElement('span');
                trophy.innerHTML = ['🥇', '🥈', '🥉'][index];
                li.querySelector('span:first-child').prepend(trophy, ' ');
            }

            rankList.appendChild(li);
        });
    }

    function updateOnlineUsers(users) {
        const userList = document.getElementById('userList');
        const onlineCount = document.getElementById('onlineCount');

        // 清空当前列表
        userList.innerHTML = '';

        // 更新在线人数
        onlineCount.textContent = users.length;

        // 动态添加用户
        users.forEach(userId => {
            const li = document.createElement('li');
            li.textContent = userId;
            userList.appendChild(li);
        });
    }

    function updateStatus(text) {
        document.getElementById('status').textContent = text;
    }

    function displayMessage(msg) {
        const messagesDiv = document.getElementById('messages');
        const messageDiv = document.createElement('div');
        console.log(msg)
        let displayText = '';
        let messageType = 'group';


        if (msg.type === 'PRIVATE') {
            // 接收方看到的格式
            displayText = `${msg.fromUser}私信给你：${msg.content}`;
            messageType = 'private-receive';
        } else if (msg.type === 'PRIVATE_SENT') {
            // 发送方看到的格式
            displayText = `你私信给${msg.toUser}：${msg.content}`;
            messageType = 'private-send';
        } else {
            // 群发消息
            displayText = `${msg.fromUser}说：${msg.content}`;
            messageType = 'group';
        }



        // 添加时间处理

        function extractTimestamp(timestamp) {
            return {
                year: timestamp.year,
                monthValue: timestamp.monthValue,
                dayOfMonth: timestamp.dayOfMonth,
                hour: timestamp.hour,
                minute: timestamp.minute,
                second: timestamp.second
            };
        }

        function createDateTimeObject(timestamp) {
            const { year, monthValue, dayOfMonth, hour, minute, second } = extractTimestamp(timestamp);
            return new Date(year, monthValue - 1, dayOfMonth, hour, minute, second);
        }

        function formatTime(date) {
            return date.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
            });
        }

        // 处理时间
        let dateTimeObj;
        if (!msg.timestamp || Object.keys(msg.timestamp).length === 0) {
            // 如果时间戳为空，使用当前时间
            dateTimeObj = new Date();
        } else {
            // 否则使用后端返回的时间
            dateTimeObj = createDateTimeObject(msg.timestamp);
        }
        const timeString = formatTime(dateTimeObj);

        messageDiv.className = `message ${messageType}`;
        messageDiv.innerHTML = `
            <div class="message-content">${displayText} <span class="timestamp">${timeString}</span></div>

        `;

        messagesDiv.appendChild(messageDiv);
        messagesDiv.scrollTop = messagesDiv.scrollHeight;
    }

    function togglePrivateField() {
        const messageType = document.getElementById('messageType').value;
        const toUserInput = document.getElementById('toUser');
        toUserInput.classList.toggle('hidden', messageType !== 'PRIVATE');
    }

    function sendMessage() {
        if (!ws || ws.readyState !== WebSocket.OPEN) {
            alert('请先连接服务器');
            return;
        }

        const content = document.getElementById('messageInput').value.trim();
        if (!content) {
            alert('请输入消息内容');
            return;
        }

        const type = document.getElementById('messageType').value;
        const toUser = type === 'PRIVATE'
            ? document.getElementById('toUser').value.trim()
            : null;

        if (type === 'PRIVATE' && !toUser) {
            alert('请输入私聊对象');
            return;
        }

        // 直接发送到服务器
        const message = {
            content: content,
            type: type,
            toUser: type === 'PRIVATE' ? toUser : null
        };
        ws.send(JSON.stringify(message));
        document.getElementById('messageInput').value = '';
    }

    // 支持回车发送消息
    document.getElementById('messageInput').addEventListener('keypress', (e) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            sendMessage();
        }
    });
</script>
</body>
</html>